package com.newa.security;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.jdbc.JdbcRealm;

public class SaltedJDBCRealm extends JdbcRealm {

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException ex) {
			System.out.print("Cant find JDBCDriver!");
		}
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken uptoken = (UsernamePasswordToken) token;
		String usersName = uptoken.getUsername();
		if (usersName == null) {
			return null;
		}
		String password;
		try {
			password = getPasswordForUser(usersName);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
		if (password == null) {
			return null;
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(usersName, password, getName());
		return info;
	}

	public String getPasswordForUser(String userName) throws SQLException {
		String url = "jdbc:mysql://localhost:3306/";
		String dbUser = "astaldo_root";
		String dbPassword = "777999qqq";
		String dbName = "astaldo_newastaldo";
		PreparedStatement statement = null;
		ResultSet set = null;
		Connection conn = DriverManager.getConnection(url + dbName, dbUser,
				dbPassword);
		statement = conn.prepareStatement(authenticationQuery);
		statement.setString(1, userName);
		set = statement.executeQuery();
		boolean hasAccount = set.next();
		if (!hasAccount) {
			return null;
		}
		String password = set.getString(1);
		
		return password;
	}
}
